package com.toune.movie.base.myview;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.toune.movie.R;
import com.vondear.rxtool.RxAppTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.view.RxToast;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;

import java.io.File;

/**
 * Created by Administrator on 2018/4/17.
 */

public class DownLoadApkDialog extends Dialog {
    private Context context;
    private Button cancelBtn,backBtn;
    private NumberProgressBar mProgressBar;

    //    private String url = "http://gdown.baidu.com/data/wisegame/00d935b62e77cfc1/weixin_780.apk";
    private String url = "";
    private DownloadRequest downloadRequest;//下载请求
    private static final String CancelSign = "CancelSign";

    public DownLoadApkDialog(Context context, String url) {
        super(context);
        this.context = context;
        this.url = url;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = this.getWindow();
        window.setGravity(17);
        window.setWindowAnimations(com.siberiadante.customdialoglib.R.style.bottom_animation);

        View view = View.inflate(context, R.layout.dialog_download_apk, null);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(view);
        WindowManager windowManager = ((Activity) context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.width = display.getWidth() * 4 / 5;
        this.getWindow().setAttributes(lp);
        this.setCanceledOnTouchOutside(false);

        mProgressBar = view.findViewById(R.id.numberProgressBar);
        backBtn = view.findViewById(R.id.bacBtn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        cancelBtn = view.findViewById(R.id.cancelBtn);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                downloadRequest.cancel();
            }
        });
        //下载文件
        //说明一下下面的几个参数
        //1.url
        //2.文件存储路径
        //3.文件名
        //4.断点是否继续
        //5.是否删除旧的
        downloadRequest = NoHttp.createDownloadRequest(url,
                RxFileTool.getSDCardPath(),
                "touneMovie.apk",
                true,
                true);
        downloadRequest.setCancelSign(CancelSign);//设置停止下载的记号
        down();
    }

    private void stop() {
        downloadRequest.cancelBySign(CancelSign);//通过记号停止下载
    }

    private int WHAT = 0;

    private void down() {
        check();
        NoHttp.getDownloadQueueInstance().add(WHAT, downloadRequest, new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {
                //下载异常
            }

            @Override
            public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
                //开始下载
                //what
                //isResume 是否重新下载
                //rangeSize 已下载文件大小
                //responseHeaders
                //allCount 文件总大小
                //int progress = (int) (rangeSize * 100 / allCount); 下载进度
                int progress = (int) (rangeSize * 100 / allCount); //下载进度
                mProgressBar.setProgress(progress);
            }

            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
                mProgressBar.setProgress(progress);
            }


            @Override
            public void onFinish(int what, String filePath) {
                //下载完成
                //filePath 文件路径
                //安装应用
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setDataAndType(Uri.parse(filePath), "application/vnd.android.package-archive");
//                context.startActivity(intent);

                File apkFile = RxFileTool.getFileByPath(filePath);
                if (!apkFile.exists()) {
                    return;
                }
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
//                if (Build.VERSION.SDK_INT >= 24) {
//                    Uri apkUri = FileProvider.getUriForFile(App.getInstance(), "com.toune.baseapp.FileProvider", apkFile);
//                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//                } else {
//                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//                }
//                context.startActivity(intent);
                RxAppTool.installApp(context, apkFile);
                dismiss();
            }

            @Override
            public void onCancel(int what) {
                //下载取消
                stop();
            }
        });
    }


    private void check() {
        // 检查之前的下载状态
        int beforeStatus = downloadRequest.checkBeforeStatus();
        switch (beforeStatus) {
            case DownloadRequest.STATUS_RESTART:
                mProgressBar.setProgress(0);
                RxToast.showToast("开始下载");
                break;
            case DownloadRequest.STATUS_RESUME:
                RxToast.showToast("正在下载");
                break;
            case DownloadRequest.STATUS_FINISH:
                mProgressBar.setProgress(100);
                RxToast.showToast("下载完成");
                break;
        }
    }
}
